import axios from 'axios';
import type { AxiosInstance } from 'axios';
import { showMessage } from '../utils/message';

const BASE_URL = 'http://localhost:8005/users';

interface UserProfile {
  id: number;
  username: string;
  email: string;
  nick_name?: string;
  created_at: string;
  last_login?: string;
}

interface UserUpdateData {
  email?: string;
  nick_name?: string;
  password?: string;
}

const api: AxiosInstance = axios.create({
  baseURL: BASE_URL,
  timeout: 5000,
});

// Response interceptor
api.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      showMessage(res);
      return Promise.reject(res);
    }
    showMessage(res);
    return res;
  },
  (error) => {
    showMessage({
      code: error.response?.status || 500,
      msg: error.response?.data?.msg || '请求失败',
    });
    return Promise.reject(error);
  }
);

const userApi = {
  // 获取用户个人信息
  async getProfile(): Promise<UserProfile> {
    const response = await api.get('/profile');
    return response.data;
  },

  // 更新用户信息
  async updateProfile(data: UserUpdateData): Promise<UserProfile> {
    const response = await api.put('/profile', data);
    return response.data;
  },

  // 获取用户提交历史
  async getSubmissionHistory(page = 1, pageSize = 10) {
    const response = await api.get('/submissions', {
      params: { page, pageSize }
    });
    return response.data;
  }
};

export default userApi;
